<template>
  <div class="app-container">
    <div class="text-right mb-4">
      <el-button size="default" type="primary" @click="handleCreated">添加群分类</el-button>

    </div>
    <el-table :data="tableData" border stripe>
      <el-table-column v-for="col in columns"
                       :key="col.id"
                       :label="col.label"
                       :prop="col.property"
                       :width="col.width">
        <template slot-scope="scope">
          <section v-if="['group_code'].includes(col.property)">
            <span v-if="scope.row.is_open_dynamic === 1">群动态</span>
            <span v-if="scope.row.is_open_party === 1">同城派对</span>
            <span v-if="scope.row.is_open_friend === 1">恋爱专线</span>
          </section>
          <section v-else-if="col.property === 'type'">
            <span v-if="scope.row.type === 'city'">同城派对</span>
            <span v-else-if="scope.row.type === 'friend'">恋爱专线</span>
            <span v-else>无</span>
          </section>
          <span v-else-if="col.property === 'icon'">
						<img :src="scope.row[col.property]" alt="">
					</span>
          <span v-else>{{ scope.row[col.property] }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="handleEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>

    </el-table>
    <cus-pagination v-show="total>0" :limit.sync="listQuery.perPage" :page.sync="listQuery.page" :total="total"
                    @pagination="getList"/>

    <!-- 新增和编辑 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="AddOrEditVisible"
      width="40%"
      @close="handleCloseDialog">
      <el-form ref="form" :inline="false" :model="form" :rules="rules" label-width="180px" size="normal">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="默认群名称" prop="group_name">
          <el-input v-model="form.group_name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="群应用（资料页）">
          <el-checkbox-group v-model="checkedIds">
            <el-checkbox v-for="item in allApplyList" :key="item.id" :label="item.id" border>{{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="群应用（聊天页）">
          <el-radio-group v-model="form.type">
            <el-radio v-for="item in allGroupApplyList" :key="item.id" :label="item.id" border>{{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传分类样式" prop="icon">
          <el-upload
            :before-upload="beforeAvatarUpload"
            :http-request="customizeUpload"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            action="#"
            class="avatar-uploader mb-4">
            <img v-if="form.icon" :src="form.icon" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-upload
            :before-upload="beforeAvatarUpload"
            :http-request="customizeUpload"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            action="#"
            class="upload-demo"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer">
				<el-button @click="AddOrEditVisible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit('form')">确定</el-button>
			</span>
    </el-dialog>


  </div>
</template>

<script>
import {CategoryAdd, CategoryEdit, getCategoryList} from "@/api/groupChat/groupCategory";

export default {
  name: '',
  data() {
    return {
      listQuery: {
        page: 1,
        perPage: 10,
      },
      form: {
        name: '',
        type: '',
        icon: '',
        is_open_dynamic: 0,
        is_open_party: 0,
        is_open_friend: 0,
        group_name: '',
      },
      checkedIds: [],
      total: 0,
      rules: {
        name: [
          {required: true, message: '请输入分类名称', trigger: 'blur'},
          {max: 11, message: '长度不能超过11个字符', trigger: 'blur'}
        ],
        group_name: [
          {required: true, message: '请输入群名称', trigger: 'blur'},
          {max: 11, message: '长度不能超过11个字符', trigger: 'blur'}
        ],
        // icon: [{required: true, message: '请上传图片', trigger: 'blur'}]
      },
      dialogTitle: '新增',
      handleMode: '',
      AddOrEditVisible: false,
      allApplyList: [
        {
          id: 1,
          name: '群动态'
        },
        {
          id: 2,
          name: '同城派对'
        },
        {
          id: 3,
          name: '恋爱专线'
        }
      ],
      allGroupApplyList: [
        {
          id: 'city',
          name: '同城派对'
        },
        {
          id: 'friend',
          name: '恋爱专线'
        }
      ],
      tableData: [],
      columns: [
        {
          id: 1,
          label: '群聊类型',
          property: 'name',
          width: 'auto'
        },
        {
          id: 2,
          label: '展示样式',
          property: 'icon',
          width: '200'
        },
        {
          id: 3,
          label: '分类ID',
          property: 'id',
          width: 'auto'
        },
        {
          id: 4,
          label: '群应用（资料页）',
          property: 'group_code',
          width: 'auto'
        },
        {
          id: 5,
          label: '群应用（聊天页）',
          property: 'type',
          width: 'auto'
        }
      ],
      row_id: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      getCategoryList(this.listQuery).then(({data}) => {
        this.tableData = data.list
        this.total = data.meta.total
        this.listLoading = false
      })
    },
    handleCreated() {
      this.dialogTitle = '新增'
      this.handleMode = 'add'
      this.AddOrEditVisible = true
    },
    handleEdit(row) {
      this.row_id = row.id
      
      this.handleMode = 'edit'
      this.dialogTitle = '编辑'
      
      getCategoryList({
        category_id: row.id
      }).then(({data}) => {
        this.form = row
        if (data.is_open_dynamic === 1) this.checkedIds.push(1)
        if (data.is_open_party === 1) this.checkedIds.push(2)
        if (data.is_open_friend === 1) this.checkedIds.push(3)
      })
      this.AddOrEditVisible = true
    },
    handleCloseDialog() {
      this.form = {
        name: '',
        type: '',
        icon: '',
        is_open_dynamic: 0,
        is_open_party: 0,
        is_open_friend: 0,
        group_name: '',
      }
      this.checkedIds = []
      // this.$refs.form.resetFields()
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isSelect()
          if (this.handleMode === 'edit') {
            CategoryEdit(this.row_id, this.form).then(res => {
              if (res.code === 200) {
                this.getList()
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.AddOrEditVisible = false
              } else {
                return false
              }
            })
          } else if (this.handleMode === 'add') {
            CategoryAdd(this.form).then(res => {
              if (res.code === 200) {
                this.getList()
                this.$message({
                  type: 'success',
                  message: '新增成功'
                })
                this.AddOrEditVisible = false
              } else {
                return false
              }
            })
          }
        } else {
          return false
        }
      })

    },
    //判断选中
    isSelect() {
      console.log(this.checkedIds)
      this.form.is_open_dynamic = this.checkedIds.includes(1) ? 1 : 0
      this.form.is_open_party = this.checkedIds.includes(2) ? 1 : 0
      this.form.is_open_friend = this.checkedIds.includes(3) ? 1 : 0
    },
    handleChecked1() {
    },
    handleChecked2() {
    },
    handleAvatarSuccess(res, file, fileList) {
      this.form.icon = this.ossLastImgUrl
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return isLt2M
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep {

  .avatar-uploader .el-upload {
    border        : 1px dashed #d9d9d9;
    border-radius : 6px;
    cursor        : pointer;
    position      : relative;
    overflow      : hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color : #409EFF;
  }

  .avatar-uploader-icon {
    font-size   : 28px;
    color       : #8c939d;
    width       : 178px;
    height      : 178px;
    line-height : 178px;
    text-align  : center;
  }

  .avatar {
    width   : 178px;
    height  : 178px;
    display : block;
  }
}
</style>